package com.gmail.viktor.yuryev.strategy;

import com.gmail.viktor.yuryev.model.ServerDetails;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;

import java.io.File;

/**
 * Created by Viktor Yuryev on 4/7/2014.
 */
public class SudoStrategy extends AbstractUploadStrategy {
    private String tempDir;
    private ServerDetails serverDetails;

    public SudoStrategy(Session session, ServerDetails serverDetails) {
        super(session);
        this.serverDetails = serverDetails;
    }


    @Override
    protected void uploadInternal(File srcFile, String destDir) throws Exception {
        tempDir = serverDetails.getServerHome() + "/" + "temp";
        sftp.cd(tempDir);
        System.out.println(tempDir);
        execCmdReturnScreenOutput("chmod 777 " + tempDir);
        sftp.put(srcFile.getAbsolutePath(), tempDir, ChannelSftp.OVERWRITE);
        String tempFile = tempDir + "/" + srcFile.getName();
        execCmdReturnScreenOutput("cp -r " + tempFile + " " + destDir);
        execCmdReturnScreenOutput("rm -rf " + tempFile);
        System.out.println("uploaded");
    }


    protected String getCommand(String cmd) {
        return serverDetails.getSudoPrefix() != null ? serverDetails.getSudoPrefix() + cmd : cmd;
    }
}
